#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 创建 socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket error");
        return 1;
    }

    // 填充服务器信息
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // 连接到服务器
    if (::connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("connect error");
        close(sockfd);
        return 1;
    }

    std::cout << "Connected to server at " << server_ip << ":" << server_port << std::endl;

    // 发送和接收数据
    char buffer[1024] = {0};
    while (true) {
        std::cout << "Please enter message: ";
        std::string message;
        std::getline(std::cin, message);

        if (message == "quit") {
            break;
        }

        // 发送消息到服务器
        if (::send(sockfd, message.c_str(), message.size(), 0) < 0) {
            perror("send error");
            break;
        }

        // 接收来自服务器的响应
        int bytes_received = ::recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        if (bytes_received > 0) {
            buffer[bytes_received] = '\0';
            std::cout << "Server response: " << buffer << std::endl;
        } else if (bytes_received == 0) {
            std::cout << "Server closed connection." << std::endl;
            break;
        } else {
            perror("recv error");
            break;
        }
    }

    // 关闭连接
    close(sockfd);
    return 0;
}